﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XToolkit.Text;
using Xwork.SEO.Providers;
using System.Threading.Tasks;
namespace Xwork.SEO
{
    /// <summary>
    /// 数据库操作
    /// </summary>
    public static class DbExtensions
    {
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="db"></param>
        /// <param name="email"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static User Reg(this Db db, string email, string password)
        {
            User user = db.Users.Add(new User { Email = email, LoginPassword = password.MD5(), EmailAuthenticated = false, CreateTime = DateTime.Now, IsAdmin = false });
            db.SaveChanges();
            return user;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="db"></param>
        /// <param name="email"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static User Login(this Db db, string email, string password)
        {
            string psw = password.MD5();
            User user = db.Users.FirstOrDefault(p => p.Email == email.Trim() && p.LoginPassword == psw);
            if (user == null)
            {
                throw new Exception("用户名或密码错误");
            }
            return user;
        }

        /// <summary>
        /// 验证密码是否正确
        /// </summary>
        /// <param name="db"></param>
        /// <param name="userId"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static bool CheckPassword(this Db db, long userId, string password)
        {
            User user = db.Users.Find(userId);
            if (user == null)
            {
                throw new Exception("用户不存在");
            }
            return user.LoginPassword == password.MD5();
        }


        public static void ChangePassword(this Db db, long userId, string oldPassword, string newPassword)
        {
            if (CheckPassword(db, userId, oldPassword))
            {
                User user = db.Users.Find(userId);
                user.LoginPassword = newPassword.MD5();
                db.SaveChanges();
            }
            else
            {
                throw new Exception("旧密码不正确");
            }
        }


        public static void SendValidateEmail(this Db db, long userId)
        { 
            
        }


        /// <summary>
        /// 跑数据
        /// </summary>
        /// <param name="db"></param>
        /// <param name="keywordId"></param>
        public static void SeachRun(this Db db, long keywordId)
        {
            SeoKeyword sk = db.SeoKeywords.Find(keywordId);
            if (sk.SearchEngines.Count == 0)
            {
                return;
            }

            foreach (var item in sk.SearchEngines)
            {
                SearchEngineProvider provider = SearchEngineProvider.GetProvider(item.Provider);
                Task<SearchResult> result = provider.DoSearch(sk.KeywordName, sk.SeoSite.SiteUrl);
                if (result.Exception != null)
                {
                    SearchResult sr = result.Result;
                    db.SeoLogs.Add(new SeoLog
                    {
                        CreateTime = DateTime.Now,
                        PageIndex = sr.PageIndex,
                        RowIndex = sr.RowIndex,
                        SearchEngineID = item.ID,
                        SeoKeywordID = sk.ID,
                        Amount = sr.Found ? (sr.PageIndex == 1 ? sk.Price : sk.Price / 2) : 0
                    });
                    //TODO 添加seo关键词消费扣款代码

                    db.SaveChanges();
                }
                else
                { 
                    //TODO 记录SEO关键词查询错误日志
                }
            }
        
        }


        /// <summary>
        /// 处理充值
        /// </summary>
        /// <param name="db"></param>
        /// <param name="topupId"></param>
        public static void HandleTopup(this Db db, long topupId)
        {
            Topup topup = db.Topups.Find(topupId);
            if (topup == null)
            {
                throw new Exception("订单ID不正确");
            }
            if (topup.Handled)
            {
                throw new Exception("订单已处理，请勿重复处理");
            }

            topup.User.UseableAmount += topup.Amount;
            topup.UseableAmount = topup.User.UseableAmount;
            topup.Handled = true;
            db.SaveChanges();
        }
    }
}
